'use strict';
const db = uniCloud.database();
const userDB = db.collection('Accounts');

exports.main = async (event, context) => {
  const { name, password } = event;
  
  if (!name || typeof name !== 'string') {
    return {
      code: 400,
      message: '姓名无效'
    };
  }
  if (!password || typeof password !== 'string') {
    return {
      code: 400,
      message: '密码无效'
    };
  }

  try {
    let result = await userDB.where({ name: name }).get();
    
    if (result.data.length > 0) {
      if (result.data.length > 1) {
        return {
          code: 600,
          data: "服务器数据异常"
        };
      }
      
      let userPWD = result.data[0].password;
      if (password === userPWD) {
        return {
          code: 200,
          data: result.data[0]._id
        };
      } else {
        return {
          code: 201,
          data: "密码错误"
        };
      }
    } else {
      return {
        code: 300,
        data: "用户不存在"
      };
    }
  } catch (error) {
    console.error('数据库查询失败：', error);
    return {
      code: 500,
      message: '服务器查询失败'
    };
  }
};